package team.archai.nexus.boot.web.filters;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import team.archai.nexus.boot.config.ArchaiNexusProperties;
import team.archai.nexus.boot.constant.HttpEnum;
import team.archai.nexus.boot.tool.HttpUtil;
import team.archai.nexus.boot.tool.Tool;
import team.archai.nexus.boot.web.response.ResultUtil;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @description: ip 校验 filter
 * @author: lishibin
 * @create: 2020-07-11 01:59
 **/
@Component
@Order(1)
public class IpFilter implements Filter {

    @Resource
    private ArchaiNexusProperties archaiNexusProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑，如果需要
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (!archaiNexusProperties.getClientIpFilterEnabled()) {
            chain.doFilter(request, response);
            return;
        }
        List<String> ipList = Tool.toStrList(archaiNexusProperties.getIpList(), ",");
        String ip = getClientIp(httpRequest);
        if (ipList.contains(ip)) {
            chain.doFilter(request, response);
            return;
        }
        HttpUtil.responseJson(response, ResultUtil.out(HttpEnum.FORBIDDEN));

    }

    @Override
    public void destroy() {
        // 清理逻辑，如果需要
    }

    private String getClientIp(HttpServletRequest request) {
        String xf = request.getHeader("X-Forwarded-For");
        if (xf == null || xf.isEmpty()) {
            return request.getRemoteAddr();
        }
        // 取第一个真实 IP
        return xf.split(",")[0].trim();
    }
}
